package com.ninong.ker.admin.service.impl;

import java.util.Arrays;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ninong.ker.admin.domain.FwFormConfig;
import com.ninong.ker.admin.domain.FwGroup;
import com.ninong.ker.admin.mapper.FwFormConfigMapper;
import com.ninong.ker.admin.mapper.FwGroupMapper;
import com.ninong.ker.admin.rest.vo.FwGroupVO;
import com.ninong.ker.admin.service.FwGroupService;
import com.ninong.ker.admin.service.dto.FwGroupDTO;
import com.ninong.ker.common.auth.SecurityAdmin;
import com.ninong.ker.common.tools.Constants;
import com.ninong.ker.common.user.OnlineUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;


/**
 * @author jmz
 */
@Service
@Transactional(rollbackFor = RuntimeException.class)
public class FwGroupServiceImpl extends ServiceImpl<FwGroupMapper, FwGroup> implements FwGroupService {

	@Autowired
	private SecurityAdmin securityAdmin;
	@Autowired
	private FwFormConfigMapper fwFormConfigMapper;

    @Override
	public PageInfo<FwGroup> listPage(FwGroupDTO dto) {
		PageHelper.startPage(dto.getCurrentPage(), dto.getPageSize());
		LambdaQueryWrapper<FwGroup> query = new LambdaQueryWrapper<>();
		query.eq(FwGroup::getDeleted, Constants.DEFAULT_YES);
		List<FwGroup> groups = baseMapper.selectList(query);
		return new PageInfo<FwGroup>(groups);
	}

	@Override
	public void delete(String[] ids) {
		List<String> idList = Arrays.asList(ids);
		idList.forEach(id -> {		
			FwGroup entity = new FwGroup();
			entity.setId(id);
			entity.setDeleted(false);
			baseMapper.updateById(entity);
		});
	}

	@Override
	public void create(FwGroup entity) {
		OnlineUser onlineUser = securityAdmin.currentUser();
		entity.setTenantId(onlineUser.getTenantId());
		saveOrUpdate(entity);
	}

	@Override
	public FwGroupVO get(String id) {
		FwGroup entity = baseMapper.selectById(id);
		if (ObjectUtils.isEmpty(entity)) {
			entity = new FwGroup();
		}
		FwGroupVO vo = new FwGroupVO();
		BeanUtils.copyProperties(entity,vo);
		LambdaQueryWrapper<FwFormConfig> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.select(FwFormConfig::getId,FwFormConfig::getName);
		vo.setConfs(fwFormConfigMapper.selectList(queryWrapper));
		return vo;
	}

	@Override
	public List<FwGroup> treeData() {
		LambdaQueryWrapper<FwGroup> query = new LambdaQueryWrapper<>();
		query.select(FwGroup::getId,FwGroup::getName);
		return baseMapper.selectList(query);
	}

}